package development.app;

import java.util.Vector;

import particle.core.tools.ByteBuffer;
import particle.core.tools.File;
import state.Clip;
import state.GameAlert;
import state.GameConstants;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.component.Event;
import state.component.EventListener;
import state.component.GameScrollBar;
import state.font.FontManager;
import state.font.ImageText;
import state.socket.DataPackage;
import state.util.GameColor;
import state.util.Hashtable;
import state.util.ImageUtil;
import state.util.array.ByteArray;
import state.util.array.StringArray;
import development.Constants;
import development.DrawUtils;
import development.Global;
import development.bean.AppFriend;
import development.group.FrmGroupKetBanMangXHChat;

public class FrmKetBan extends GameForm implements EventListener {
  private StringArray KETBAN_NAME = new StringArray(new String[]{ "Tìm bạn nữ", "Tìm bạn nam" },2);
  private StringArray KETBAN_CODE = new StringArray(new String[] { "PG_NU", "PG_NAM" },2);

  public static final int GET_PROVINCE_LIST_REQUEST = 1401;
  public static final int GET_PROVINCE_LIST_RESPONSE = 1402;
  public static final int GET_FRIEND_LIST_REQUEST = 1403;
  public static final int GET_FRIEND_LIST_RESPONSE = 1404;
  public static final int GET_PROVINCE_COUNT_RESPONSE = 1405;
  public static final int GET_FRIEND_COUNT_RESPONSE = 14016;
  public static final int GET_PAID_REQUEST = 1407;
  public static final int GET_PAID_RESPONSE = 1408;

  private GameImage[] itemsImages;
  private ImageText text8;
  private int chooseIndex;
  boolean isshowdetail;
  private String[] listTypeDraw = new String[] { "drawmain", "drawcategory", "drawcontentlist", "drawcontentdata" };
  int currentpage;
  private int HOZ_DISTANCE = 0;
  private int VER_DISTANCE = 35;
  private int ContentList_HOZ_DISTANCE = 0;
  private int ContentList_VER_DISTANCE = 50;
  private int DX = 0;
  private int DY = 25;
  private int NUMBER_OF_ITEM_PER_ROW = 1;
  private int numberOfItem;
  int countpercent;
  String typeDraw;
  String sexcode;
  String provincecode;
  int dx;
  int dy;
  int step;// buoc scoll
  private GameScrollBar scrollBar;
  private Clip textView;
  private final int DEFAULT_TEXT_X = 10;
  private final int DEFAULT_TEXT_Y = 25;
  private final int STEPSCROLLBAR = 2;
  // category
  private String[] provinces;
  private GameImage itemsListProvince;
  int provincetotalcount;
  // Friend list
  int friendtotalcount;
  int MAXPAGE = 1;
  int MAXROW = 7;
  int ispaiddownload;
  int ispaidfriendload;
  private GameImage previewImages;
  // scoll
  public int minTextY;
  String fileName;
  boolean isCompleted;
  private Vector KetBanProvinceList;
  private Vector KetBanFriendList;
  private AppFriend appfriends;
  private static GameForm singleton;
  boolean isOnRecieveData;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmKetBan();
    }
    return singleton;
  }

  public void init(Hashtable parameters) {
    ispaiddownload = -1;
    numberOfItem = KETBAN_CODE.len();
    itemsImages = new GameImage[2];
    itemsImages[0] = ImageUtil.getImage(Constants.KET_BAN_CATEGORY, "icon_female.png");
    itemsImages[1] = ImageUtil.getImage(Constants.KET_BAN_CATEGORY, "icon_male.png");
    itemsListProvince = ImageUtil.getImage(Constants.KET_BAN_CATEGORY, "icon_heart.png");
    isOnRecieveData = false;
    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    currentpage = 0;
    chooseIndex = 0;
    countpercent = 100;
    provinces = new String[3];
    typeDraw = listTypeDraw[0];
    provincetotalcount = 0;
    friendtotalcount = 0;
    sexcode = KETBAN_CODE.array[0];
    dx = DX;
    dy = DY;
    KetBanProvinceList = new Vector();
    KetBanFriendList = new Vector();
    appfriends = new AppFriend();
    step = VER_DISTANCE;
    ispaiddownload = 0;
    ispaidfriendload = 0;
    isCompleted = false;

    textView = new Clip(DEFAULT_TEXT_X, DEFAULT_TEXT_Y, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT - 50);
    scrollBar = new GameScrollBar(Constants.SCREEN_WIDTH - 5, 25, 5, Constants.SCREEN_HEIGHT - 50, textView, _manager);
    _manager.enableTouchPad();
  }

  public void draw(Graphics g) {
    DrawUtils.drawAppBackground(g);
    FrmGroupKetBanMangXHChat frmGroupKetBanMangXHChat = (FrmGroupKetBanMangXHChat) FrmGroupKetBanMangXHChat.instance();
    frmGroupKetBanMangXHChat.getMultiTab().setTitle(0, "Kết bạn");
    if (typeDraw.equalsIgnoreCase(listTypeDraw[0])) {
      drawMain(g);
    } else if (typeDraw.equalsIgnoreCase(listTypeDraw[1])) {
      drawCategory(g);
    } else if (typeDraw.equalsIgnoreCase(listTypeDraw[2])) {
      drawContentList(g);
    } else if (typeDraw.equalsIgnoreCase(listTypeDraw[3])) {
      drawContentData(g);
    }
  }

  private void drawMain(Graphics g) {
    DrawUtils.setBottomBar(_manager, "", "Chọn", "Trở về");
    if (numberOfItem != 0) {
      for (int row = 0; row < numberOfItem; row++) {
        int x = dx + HOZ_DISTANCE * (row % NUMBER_OF_ITEM_PER_ROW);
        int y = dy + VER_DISTANCE * (row / NUMBER_OF_ITEM_PER_ROW);
        if (chooseIndex == row) {
          g.setColor(0x4EA2D0);
          g.fillRect(x, y, GameConstants.SCREEN_WIDTH, VER_DISTANCE);
        }
        g.drawImage(itemsImages[row], x + 24, y + 15, GameConstants.CENTER_ANCHOR);
        text8.drawString2(g, KETBAN_NAME.array[row], GameColor.YELLOW_CODE, x + 38, y + 5, GameConstants.TOP_LEFT_ANCHOR);
        g.setColor(0xC0C0C0);
        g.drawLine(0, y + VER_DISTANCE, GameConstants.SCREEN_WIDTH, y + VER_DISTANCE);
      }
    }
  }

  private void drawCategory(Graphics g) {
    if(countpercent < 100)
      DrawUtils.setBottomBar(_manager, "","Loading... "+ countpercent +"%", "Trở về");
    else
      DrawUtils.setBottomBar(_manager, "", "Chọn", "Trở về");
    if (isOnRecieveData) {
      int x = 0;
      int y = 0;
      if (!KetBanProvinceList.isEmpty()) {
        for (int row = 0; row < numberOfItem; row++) {
          x = dx + HOZ_DISTANCE * (row % NUMBER_OF_ITEM_PER_ROW);
          y = dy + VER_DISTANCE * (row / NUMBER_OF_ITEM_PER_ROW);
          if (chooseIndex == row) {
            g.setColor(0x4EA2D0);
            g.fillRect(x, y, GameConstants.SCREEN_WIDTH, VER_DISTANCE);
          }
          provinces = (String[]) KetBanProvinceList.elementAt(row);
          g.drawImage(itemsListProvince, x + 24, y + 12, GameConstants.CENTER_ANCHOR);
          text8.drawParagraph2(g, provinces[1], GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH - 10, x + 38, y + 6, scrollBar);
          g.setColor(0xC0C0C0);
          g.drawLine(0, y, GameConstants.SCREEN_WIDTH, y);
        }
        scrollBar.draw(g);
      } else {
        GameGlobal.alert.showAlert1(this, GameAlert.YES_BUTTON, StringArray.create2( "Dữ liệu đang ", "được cập nhập", "Bạn truy cập lại sau." ), 155);
      }
    }
  }

  private void drawContentList(Graphics g) {
    if(countpercent < 100) {
      DrawUtils.setBottomBar(_manager, "","Loading... "+ countpercent +"%", "Trở về");
    } else {
      DrawUtils.setBottomBar(_manager, "", "Chọn", "Trở về");
    }
    
    if (isOnRecieveData) {
      int x = 0;
      int y = 0;
      if (!KetBanFriendList.isEmpty()) {
        for (int row = 0; row < numberOfItem; row++) {
          x = dx + ContentList_HOZ_DISTANCE * (row % NUMBER_OF_ITEM_PER_ROW);
          y = dy + ContentList_VER_DISTANCE * (row / NUMBER_OF_ITEM_PER_ROW);
          if (chooseIndex == row) {
            g.setColor(0x4EA2D0);
            g.fillRect(x, y, GameConstants.SCREEN_WIDTH, ContentList_VER_DISTANCE);
          }
          appfriends = (AppFriend) KetBanFriendList.elementAt(row);
          g.drawImage(appfriends.avatarimage, x + 33, y + 26, GameConstants.CENTER_ANCHOR);
          text8.drawParagraph2(g, appfriends.name, GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH - 10, x + 70, y + 4, scrollBar);
          text8.drawString2(g, appfriends.detailmodified, GameColor.YELLOW_CODE, x + 70, y + 26, GameConstants.TOP_LEFT_ANCHOR);
          g.setColor(0xC0C0C0);
          g.drawLine(0, y, GameConstants.SCREEN_WIDTH, y);
        }
        scrollBar.draw(g);
      }
    }
    FrmGroupKetBanMangXHChat frmGroupKetBanMangXHChat = (FrmGroupKetBanMangXHChat) FrmGroupKetBanMangXHChat.instance();
    frmGroupKetBanMangXHChat.getMultiTab().setTitle(0, "< " + ((currentpage + 1) + "/" + MAXPAGE + " >"));
  }

  private void drawContentData(Graphics g) {
    DrawUtils.setBottomBar(_manager, "Tải ảnh", "Làm quen", "Trở về");
    int x = dx;
    int y = dy;
    g.drawImage(previewImages, x + 10, y + 5, GameConstants.TOP_LEFT_ANCHOR);
    // neu ket ban ok
    if (ispaidfriendload == 1) {
      text8.drawParagraph(g, appfriends.getDetail().trim(), GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH - 20, x + 10, y + previewImages.getHeight() + 10);
    } else {
      text8.drawParagraph(g, appfriends.getDetailModified().trim(), GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH - 20, x + 10, y + previewImages.getHeight() + 10);
      g.setColor(0xC0C0C0);
      g.drawLine(0, y + previewImages.getHeight() + 10 + 60, GameConstants.SCREEN_WIDTH, y + previewImages.getHeight() + 10 + 60);
      text8.drawParagraph(g, "Bạn có thể tải ảnh hoặc làm quen để nhận số điện thoại và nick yahoo của PG này.", GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH - 20, x + 10, y + previewImages.getHeight() + 10 + 62);
    }
  }
  
  public void onActionPerform(Event event) {
  }

  public void keyReleased(int keyCode) {
    if (countpercent == 100) {
      switch (keyCode) {
      case Key.DOWN:
        chooseIndex = (chooseIndex + NUMBER_OF_ITEM_PER_ROW > numberOfItem - 1) ? chooseIndex : chooseIndex + NUMBER_OF_ITEM_PER_ROW;
        if (typeDraw.equalsIgnoreCase(listTypeDraw[2])) {
          step = ContentList_VER_DISTANCE;
        } else {
          step = VER_DISTANCE;
        }
        int down = dy + step * (chooseIndex / NUMBER_OF_ITEM_PER_ROW);
        if (typeDraw.equalsIgnoreCase(listTypeDraw[3])) {
          dy -= step;
        } else {
          if (down > GameConstants.SCREEN_HEIGHT - (50 + DrawUtils.getBottomBarHeight() + 25)) {
            dy -= step;
          }
        }
        break;
      case Key.UP:
        chooseIndex = (chooseIndex - NUMBER_OF_ITEM_PER_ROW < 0) ? chooseIndex : chooseIndex - NUMBER_OF_ITEM_PER_ROW;
        if (typeDraw.equalsIgnoreCase(listTypeDraw[2])) {
          step = ContentList_VER_DISTANCE;
        } else {
          step = VER_DISTANCE;
        }
        int up = dy + step * (chooseIndex / NUMBER_OF_ITEM_PER_ROW);
        if (up < 25) {
          dy += step;
        }
        break;
      case Key.LEFT:
        if (typeDraw.equalsIgnoreCase(listTypeDraw[2])) {
          currentpage = (currentpage - 1 < 0) ? 0 : currentpage - 1;
          Update();
          chooseIndex = 0;
        }
        break;
      case Key.RIGHT:
        if (typeDraw.equalsIgnoreCase(listTypeDraw[2])) {
          currentpage = (currentpage + 1 > MAXPAGE - 1) ? currentpage : currentpage + 1;
          Update();
          chooseIndex = 0;
        } else {
          FrmGroupKetBanMangXHChat.setTab(1);
        }
        break;
      case Key.SOFT_LEFT:
        if (typeDraw.equalsIgnoreCase(listTypeDraw[3])) {
          GameGlobal.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create2( "Tải ành bạn sẽ ", "phải trả phí "+appfriends.getMoney()+"$", "Bạn có đồng ý không?" ), 55);
          break;
        }
      case Key.FIRE:
        if (typeDraw.equalsIgnoreCase(listTypeDraw[0])) {
          dy = DY;
          countpercent = 0;
          DataPackage dataPackage = DataPackage.createDataPackage1(GET_PROVINCE_LIST_REQUEST);
          dataPackage.putString(KETBAN_CODE.array[chooseIndex]);
          Global.appClient.write(dataPackage);
          sexcode = KETBAN_CODE.array[chooseIndex];
          typeDraw = listTypeDraw[1];
          numberOfItem = 0;
          chooseIndex = 0;
          KetBanProvinceList = new Vector();
          Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
        } else if (typeDraw.equalsIgnoreCase(listTypeDraw[1])) {
          dy = DY;
          countpercent = 0;
          provinces = (String[]) KetBanProvinceList.elementAt(chooseIndex);
          provincecode = provinces[0];
          DataPackage dataPackage = DataPackage.createDataPackage1(GET_FRIEND_LIST_REQUEST);
          dataPackage.putInt(1); // current page
          dataPackage.putInt(MAXROW); // page size
          dataPackage.putString(provincecode);
          Global.appClient.write(dataPackage);
          Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
          typeDraw = listTypeDraw[2];
          numberOfItem = 0;
          chooseIndex = 0;
        } else if (typeDraw.equalsIgnoreCase(listTypeDraw[2])) {
          dy = DY;
          appfriends = (AppFriend) KetBanFriendList.elementAt(chooseIndex);
          previewImages = GameImage.createImage(appfriends.getPreview(), 0, appfriends.getPreview().len());
          typeDraw = listTypeDraw[3];
        } else {
          GameGlobal.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create2( "Làm quen bạn sẽ", "phải trả phí "+appfriends.getMoney()+"$", "Bạn có đồng ý không?" ), 56);
        }
        break;
      case Key.SOFT_RIGHT:
        dy = DY;
        chooseIndex = 0;
        if (typeDraw.equalsIgnoreCase(listTypeDraw[3])) {
          typeDraw = listTypeDraw[2];
          ispaiddownload = 0;
          ispaidfriendload = 0;
        } else if (typeDraw.equalsIgnoreCase(listTypeDraw[2])) {
          KetBanFriendList = new Vector();
          typeDraw = listTypeDraw[1];
          numberOfItem = KetBanProvinceList.size();
          MAXPAGE = (int) Math.ceil((float) provincetotalcount / (float) MAXROW);
          currentpage = 0;
        } else if (typeDraw.equalsIgnoreCase(listTypeDraw[1])) {
          isOnRecieveData = false;
          KetBanProvinceList = new Vector();
          typeDraw = listTypeDraw[0];
          numberOfItem = KETBAN_CODE.len();
        } else {
          parentGroup.goBack();
        }
        break;
      }
    }
  }

  private void Update() {
    dy = 25;
    countpercent = 0;
    numberOfItem = 0;
    KetBanFriendList = new Vector();
    isOnRecieveData = false;
    DataPackage dataPackage = DataPackage.createDataPackage1(GET_FRIEND_LIST_REQUEST);
    dataPackage.putInt(currentpage + 1); // current page
    dataPackage.putInt(MAXROW); // page size
    dataPackage.putString(provincecode);
    Global.appClient.write(dataPackage);
  }

  public void onRecieveData(DataPackage dataPackage) {
    int header = dataPackage.getHeader();
    GameGlobal.systemCanvas.hideAlert();
    switch (header) {
    case GET_PROVINCE_COUNT_RESPONSE:
      provincetotalcount = dataPackage.nextInt();
      MAXPAGE = (int) Math.ceil((float) provincetotalcount / (float) MAXROW);
      break;
    case GET_PROVINCE_LIST_RESPONSE:
      KetBanProvinceList.addElement(new String[] { dataPackage.nextString(), dataPackage.nextString() });
      countpercent = dataPackage.nextInt();
      numberOfItem = KetBanProvinceList.size();
      isOnRecieveData = true;
      break;
    case GET_FRIEND_COUNT_RESPONSE:
      friendtotalcount = dataPackage.nextInt();
      if (friendtotalcount == 0) {
        Global.alert.showAlert2(this, GameAlert.OK_TYPE, "Chưa có dữ liệu của tình thành này.", 54);
      }
      MAXPAGE = (int) Math.ceil((float) friendtotalcount / (float) MAXROW);
      break;
    case GET_FRIEND_LIST_RESPONSE:
      AppFriend appfriend = new AppFriend();
      appfriend.id = dataPackage.nextString();
      appfriend.name = dataPackage.nextString();
      appfriend.provincecode = dataPackage.nextString();
      appfriend.avatar = dataPackage.nextByteArray();
      appfriend.preview = dataPackage.nextByteArray();
      appfriend.detail = dataPackage.nextString();
      appfriend.detailmodified = dataPackage.nextString();
      countpercent = dataPackage.nextInt();
      appfriend.avatarimage = GameImage.createImage(appfriend.getAvatar(), 0, appfriend.getAvatar().len());
      KetBanFriendList.addElement(appfriend);
      numberOfItem = KetBanFriendList.size();
      isOnRecieveData = true;
      break;
    case GET_PAID_RESPONSE:

      String code = dataPackage.nextString();
      if (code.endsWith("download"))
        ispaiddownload = dataPackage.nextInt();
      else
        ispaidfriendload = dataPackage.nextInt();
      if (ispaiddownload == 1) {
        // TODO: không hiển thị được phần chọn folder để save file, save file vào đường dẫn mặc định
//        GameGlobal.alert.showCustomUIAlert(frmListFile, 100);
      }
      break;
    }
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if (alertId == 54) { //
      countpercent = 100;
      KetBanFriendList = new Vector();
      typeDraw = listTypeDraw[1];
      numberOfItem = KetBanProvinceList.size();
      MAXPAGE = (int) Math.ceil((float) provincetotalcount / (float) MAXROW);
    }
    if (alertId == 55 && eventType == GameAlert.YES_BUTTON) { // download
      // Gui package tinh tien
      int money = 5;
      DataPackage dataPackage = DataPackage.createDataPackage1(GET_PAID_REQUEST);
      dataPackage.putString("download");
      dataPackage.putInt(money); // number money to paid
      Global.appClient.write(dataPackage);
    }
    if (alertId == 56 && eventType == GameAlert.YES_BUTTON) { //
      int money = 15;
      DataPackage dataPackage = DataPackage.createDataPackage1(GET_PAID_REQUEST);
      dataPackage.putString("friend");
      dataPackage.putInt(money); // number money to paid
      Global.appClient.write(dataPackage);
    }
    if (alertId == 100) {
      String filename = appfriends.getID() + ".png";
//      String filePath = frmListFile.returnFolderPath;
      doDownload("", filename, appfriends.getPreview());
    }
  }

  public void destroy() {
    numberOfItem = 0;
    itemsImages = null;
    itemsListProvince = null;
    text8 = null;
    KetBanProvinceList = null;
    KetBanFriendList = null;
    typeDraw = null;
  }

  public void doDownload(String pathfile, String fileName1, ByteArray byteToSave) {
    String pathToSave = pathfile + fileName1;
    ByteBuffer byteBuffer = new ByteBuffer();
    byteBuffer.appendBytes(byteToSave.array, byteToSave.len());
    File file = File.openFile(pathToSave, File.ModeWrite);
    file.write(byteBuffer);
    file.close();
    isCompleted = true;
    ispaiddownload = 0;
  }
}
